package com.xzit.rcpyxt.service.impl;

import com.xzit.rcpyxt.constant.MessageCode;
import com.xzit.rcpyxt.dto.CourseClassListRequest;
import com.xzit.rcpyxt.dto.InsertCousrClassRequest;
import com.xzit.rcpyxt.entity.*;
import com.xzit.rcpyxt.exceptions.CustomeException;
import com.xzit.rcpyxt.mapper.*;
import com.xzit.rcpyxt.service.SignInService;
import com.xzit.rcpyxt.utils.LocationUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class SignInServiceImpl implements SignInService {

    @Autowired
    private SignInMapper signInMapper;
    @Autowired
    private CourseClassMapper courseClassMapper;
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private HistoricalMapper historicalMapper;
    @Autowired
    private TeacherClassMapper teacherClassMapper;

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public void signIn(SignIn signIn) {
        if (signIn.getStudentId() == 0) {
            throw new CustomeException(MessageCode.PARAME_ERROR.getCode(), "学生id不能为空！");
        }
        if (signIn.getCourseClassId() == 0) {
            throw new CustomeException(MessageCode.PARAME_ERROR.getCode(), "课程id不能为空！");
        }
        if (StringUtils.isBlank(signIn.getAddress())) {
            throw new CustomeException(MessageCode.PARAME_ERROR.getCode(), "签到地址名不能为空！");
        }
        if (StringUtils.isBlank(signIn.getLongitude())) {
            throw new CustomeException(MessageCode.PARAME_ERROR.getCode(), "签到经度不能为空！");
        }
        if (StringUtils.isBlank(signIn.getLatitude())) {
            throw new CustomeException(MessageCode.PARAME_ERROR.getCode(), "签到纬度不能为空！");
        }
        CourseClass courseClass = courseClassMapper.selectByPrimaryKey(signIn.getCourseClassId());
        if (courseClass == null) {
            throw new CustomeException(MessageCode.DATA_NOT_EXISTS_ERROR.getCode(), "该课程不存在！");
        }
        switch (courseClass.getSignInStatus()) {
            case 0:
                throw new CustomeException(MessageCode.DATA_ERROR.getCode(), "该课程还不能开始签到！");
            case 2:
                throw new CustomeException(MessageCode.DATA_ERROR.getCode(), "该课程已经结束签到！");
        }
        Double aLong = Double.valueOf(courseClass.getLongitude());
        Double aLat = Double.valueOf(courseClass.getLatitude());
        Double bLong = Double.valueOf(signIn.getLongitude());
        Double bLat = Double.valueOf(signIn.getLatitude());
        double distance = LocationUtil.getDistance( aLat, aLong, bLat, bLong);
        if (distance > 100) {
            throw new CustomeException(MessageCode.SIGN_IN_ERROR);
        }
        SignIn s = signInMapper.selectBySignIn(signIn);
        if(s != null){
            throw new CustomeException(MessageCode.DATA_ERROR.getCode(), "已经签到过，不能继续签到！");
        }
        signIn.setStatus(0);
        int success = signInMapper.insertBySignIn(signIn);
        if (success <= 0) {
            throw new CustomeException(MessageCode.SIGN_IN_ERROR.getCode(), "签到失败！");
        }

        Historical historical = new Historical();
        historical.setType(1);
        historical.setUserId(signIn.getStudentId());
        historical.setTitle("签到");
        historical.setContent("您于" + sdf.format(new Date()) + " 在" +  signIn.getAddress() + "进行了签到!");
        Course course = courseMapper.selectByPrimaryKey(courseClass.getCourseId());
        historical.setCourseName(course != null ? course.getName() : "");
        historical.setStatus(0);
        historicalMapper.insertByHistorical(historical);
    }

    @Override
    public void stopSign(CourseClass aClass) {
        List<Student> students = studentMapper.selectByAllClassStudentList(aClass.getClassId());
        List<SignIn> signIns = signInMapper.selectByCourseClassSignIn(aClass.getId());
        List<Student> signInStudent = new ArrayList<>();
        for (Student student: students) {
            for (SignIn signIn: signIns) {
                if (student.getId() == signIn.getStudentId()) {
                    signInStudent.add(student);
                }
            }
        }
        students.removeAll(signInStudent);
        for (Student student: students) {
            SignIn signIn = new SignIn();
            signIn.setCourseClassId(aClass.getId());
            signIn.setStudentId(student.getId());
            signIn.setStatus(1);
            signInMapper.insertBySignIn(signIn);
            //生成未签到数据
            Historical historical = new Historical();
            historical.setType(1);
            historical.setUserId(signIn.getStudentId());
            historical.setTitle("未签到");
            historical.setContent("您于" + sdf.format(new Date()) + " 在" +  aClass.getAddress() + "未进行签到!");
            Course course = courseMapper.selectByPrimaryKey(aClass.getCourseId());
            historical.setCourseName(course != null ? course.getName() : "");
            historical.setStatus(1);
            historicalMapper.insertByHistorical(historical);
        }
    }

    @Override
    public void bathAddCourseClass(InsertCousrClassRequest insertCousrClassRequest) {
        int teacherId = insertCousrClassRequest.getTeacherId();
        if (teacherId == 0) {
            throw new CustomeException(MessageCode.PARAME_ERROR.getCode(), "老师id不能为空！");
        }

        CourseClassListRequest courseClassListRequest = new CourseClassListRequest();
        courseClassListRequest.setTeacherId(teacherId);
        courseClassListRequest.setStartTime(getArt());
        List<CourseClass> courseClasses = courseClassMapper.selectByCourseClassAllList(courseClassListRequest);
        if (courseClasses.size() > 3) {
            throw new CustomeException(MessageCode.PARAME_ERROR.getCode(), "该老师已经批量添加过课程了！");
        }

        //生成随机课程id
        int []courses = {266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289};
        Date currentDate = new Date();
        if (getHour(currentDate) < 11) {
            currentDate = getArt();
            currentDate = getNewHour(currentDate, 9);
        }

        if (teacherId != 0) {
            List<TeacherClass> teacherClasses = teacherClassMapper.selectByTeacherClassAllList(teacherId);
            for (TeacherClass teacherClass:teacherClasses) {
                for (int i = 0; i < 30; i++) {
                    for (int j = 0; j < 10; j++) {
                        CourseClass courseClass = new CourseClass();
                        courseClass.setCourseId(courses[(0 + (int) (Math.random() * courses.length - 1))]);
                        courseClass.setCreateTime(currentDate);
                        courseClass.setStartTime(getNewHour(getNewDay(currentDate, i), j));
                        courseClass.setEndTime(getNewHour(getNewDay(currentDate, i), (j + 1)));
                        courseClass.setClassId(teacherClass.getClassId());
                        courseClass.setTeacherId(teacherId);
                        courseClass.setSignInStatus(0);
                        courseClass.setAddress("徐州工程学院-敬业楼");
                        courseClass.setLongitude("118.76295");
                        courseClass.setLatitude("32.06071");
                        courseClass.setRemark("徐州工程学院");
                        courseClassMapper.insertByCourseClasss(courseClass);
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        System.out.println(new SignInServiceImpl().getArt().getTime());
    }

    public int getHour (Date currentDate) {
        Calendar c = Calendar.getInstance();
        c.setTime(currentDate);
        long now = c.getTimeInMillis();

        c.add(Calendar.DAY_OF_MONTH, 1);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);

        long millis = c.getTimeInMillis() - now;
        return (int)millis / 1000 / 3600;
    }

    public Date getArt () {
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.DAY_OF_MONTH, 1);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        return c.getTime();
    }

    public Date getNewDay(Date cur, int count) {
        Calendar c = Calendar.getInstance();
        c.setTime(cur);   //设置时间
        c.add(Calendar.DATE, count); //日期分钟加1,Calendar.DATE(天),Calendar.HOUR(小时)
        Date date = c.getTime(); //结果
        return date;
    }

    public Date getNewHour(Date cur, int count) {
        Calendar c = Calendar.getInstance();
        c.setTime(cur);   //设置时间
        c.add(Calendar.HOUR, count); //日期分钟加1,Calendar.DATE(天),Calendar.HOUR(小时)
        Date date = c.getTime(); //结果
        return date;
    }

}